from selenium import webdriver
from time import sleep
from selenium.webdriver.common.by import By
import csv


def writecsv(item):
    with open('工程建设01.csv', 'a', encoding='utf-8', newline='') as f:
        wir = csv.writer(f)
        try:
            wir.writerow(item)
        except:
            print('error')


# 标准号，p_id，标准链接url
def item():
    driver = webdriver.Chrome(r'E:\Google\chromedriver.exe')

    driver.get('https://www.biaozhun.org/')
    # 点击进入工程建设
    driver.find_element_by_xpath('/html/body/div[3]/div[2]/table/tbody/tr[3]/td[2]/a').click()
    sleep(1)
    for i in range(1, 11):
        driver.get('https://www.biaozhun.org/P/list_20.html')
        # 获取标准号
        a = driver.find_element(By.XPATH, '/html/body/div[3]/div[1]/div[2]/ul/li[' + str(i) + ']/div/div/a[2]')
        sleep(1)
        #  获取标准链接URL
        b = a.get_attribute('href')
        sleep(1)
        # print(b)
        title = b.split('.org/P/')
        rec = title[1]
        Rec = rec.split('.')

        # 点击进入详情页
        d = driver.find_element(By.XPATH, '/html/body/div[3]/div[1]/div[2]/ul/li[1]/div/div/a[2]')
        sleep(1)
        e = d.get_attribute('href')
        # 操作新窗口
        windows = driver.window_handles
        driver.switch_to.window(windows[-1])

        lists = [a.text, Rec[0], b]
        print(lists)
        # writecsv(lists)


# 下载链接1
def itemone():
    driver = webdriver.Chrome(r'E:\Google\chromedriver.exe')

    driver.get('https://www.biaozhun.org/')
    # 点击进入工程建设
    driver.find_element_by_xpath('/html/body/div[3]/div[2]/table/tbody/tr[3]/td[2]/a').click()
    sleep(1)
    for i in range(1, 11):
        # 点击进入详情页
        driver.get('https://www.biaozhun.org/P/list_20.html')
        driver.find_element(By.XPATH, '/html/body/div[3]/div[1]/div[2]/ul/li[' + str(i) + ']/div/div/a[2]').click()
        sleep(1)
        # 操作新窗口
        windows = driver.window_handles
        driver.switch_to.window(windows[-1])
        # 点击本地下载
        driver.find_element(By.XPATH, '/html/body/div[3]/div[1]/div[2]/table/tbody/tr[11]/td[2]/span').click()
        sleep(1)
        # 操作新窗口
        windows = driver.window_handles
        driver.switch_to.window(windows[-1])

        # 下载链接1
        xz = driver.find_element(By.XPATH, '/html/body/div[3]/div[1]/div[2]/table/tbody/tr[2]/td/ul/li[1]/a')
        c = xz.get_attribute('href')

        hand = driver.window_handles
        driver.switch_to.window(hand[2])
        lists = [c]
        print(lists)
        # writecsv(lists)

# itemone()
#
# item()
